﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using POCOS;
using DAL;
using GUI.Models;
using BLL;
using BLL.Interfaces;
using System.Linq.Expressions;
using System.IO;
using GUI.Models.ModelArt;
using GUI.Infrastructure;
using WebMatrix.WebData;
using GUI.Models.AdminModels;
using System.Threading;
using System.Data.Objects.DataClasses;
using System.Web.Security;
using System.Transactions;
using Microsoft.Web.WebPages.OAuth;
using DotNetOpenAuth.AspNet;
using System.Text;
using GUI.Mailers;
using System.Data.SqlClient;
using GUI.Filters;



namespace GUI.Controllers
{





      [LogAttribute]
    public class AccountController : Controller
    {
        private AuteurContext db = new AuteurContext();
        IAuteurServices _auteurService;
      static  ILogsServices _logservices;
        UserProfileServices _userpro = new UserProfileServices();

        public AccountController(IAuteurServices auteurService)
        {
            this._auteurService = auteurService;
            
        }


        #region knockoutTst
        // profile knockout js 
          [Authorize(Roles = "Admin")]
        public JsonResult GetProfile()
        {
            var Profiles =db.UserProfiles.ToList();
           
            return Json(Profiles, JsonRequestBehavior.AllowGet);
        }
          [Authorize(Roles = "Admin")]
        public JsonResult EditProfile (UserProfile model)
        {
            var t = db.UserProfiles.Find(model.UserId);
            if (t == null)
            {
                return Json(new { Result = "Ko" });
            }
            db.Entry(t).State = EntityState.Modified;

            return Json(new { Result="Ok"});
        }


        #endregion

                [Authorize(Roles = "Admin")]
                      #region Jtable
        //jtable List Authors 
        [HttpPost]
        public JsonResult AccountList(int jtStartIndex = 0, int jtPageSize = 0, string jtSorting = null)
        {
            try
            {
                Thread.Sleep(200);
                int authorcount = _auteurService.GetAuthorCount();
                var authors = _auteurService.GetAuthors(jtStartIndex, jtPageSize, jtSorting);


                //_articleServices._articleServices



                var result = from x in  authors
                          

                             select new AccountAuthorModel
                             {
                                 Id = x.Id,
                                 Name = x.Name,
                                 Lastname = x.Lastname,
                                 Adressmail = x.Adressmail,
                                 Profil = x.Profil,
                                 UserProfileId = x.UserProfileId

                             };
                List<AccountAuthorModel> accModelAuthorList = new List<AccountAuthorModel>();

                foreach (var item in result)
                {
                    AccountAuthorModel accModel = new AccountAuthorModel();
                      accModel.Id = item.Id;
                    accModel.Name = item.Name;
                    accModel.Lastname = item.Lastname;
                    accModel.Adressmail = item.Adressmail;
                    accModel.Profil = item.Profil;
                    accModel.UserProfileId = item.UserProfileId;
                    accModel.userPr = db.UserProfiles.Where(x => x.UserId == item.UserProfileId).FirstOrDefault().UserName;
                    //accModel.RoleAccount = Roles.GetRolesForUser(accModel.userPr);
                    //ViewBag.roleaccount = accModel.RoleAccount;
                    accModelAuthorList.Add(accModel);
                }
              
  return Json(new { Result = "OK", Records = accModelAuthorList, TotalRecordCount = authorcount }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return Json(new { Result = "ERROR", Message = ex.Message });
            }
        }


        
    [HttpPost]
    public JsonResult GetRolesOptions()
    {
        try
        {
            var cities = Roles.GetAllRoles();
            return Json(new { Result = "OK", Options = cities });
        }
        catch (Exception ex)
        {
            return Json(new { Result = "ERROR", Message = ex.Message });
        }
    }

       
        
         

        //Index
      
        public ActionResult Index()
        {
            ViewBag.msg = Roles.GetAllRoles();
       
          
            return View();
        }

      

      
        //Delete authors
        [HttpPost]
        public JsonResult DeleteAuthor(int Id)
        {
            var author = _auteurService.Find(Id);
          
                try
                {
                    Thread.Sleep(50);


                    _auteurService.DeleteAuteur(author.Id);
                    return Json(new { Result = "OK" });

                }

                catch (Exception ex)
                {
                    return Json(new { Result = "ERROR", Message = ex.Message });
                }
            
        }
          [HttpPost]
        public JsonResult UpdateAuthor(AccountAuthorModel model)

        {
           // var author = _auteurService.GetAuteurById(model.Id);
              var author=db.Auteurs.Include("UserProfile").FirstOrDefault(e=>e.Id==model.Id);
            UserProfile userpr = db.UserProfiles.Find(author.Id);
            if (author == null )
            {
           
                return Json(new { Status = "Failed" }, JsonRequestBehavior.AllowGet);
            }
            else
            {
                
                author.Name = model.Name;
                author.Lastname = model.Lastname;
                author.Profil = model.Profil;
                author.Adressmail = model.Adressmail;
                
              
                if (userpr != null)
                {
                    userpr.UserName = model.userPr;
                 
                }

                //if (!Roles.IsUserInRole(model.userPr.ToString(), model.RoleAccount[0]))
                //{
                //    Roles.AddUserToRole(model.userPr.ToString(), model.RoleAccount[0]);
                //}
                db.SaveChanges();


                return Json(new { Result = "OK" });
            }
            
        
        }




          #region  child author role
          [HttpPost]
        
          public JsonResult Getroles(string userid)
          {
              try
              {
                  var r = Roles.GetRolesForUser(userid).ToList();
                  List<RoleModel> rolelst = new List<RoleModel>();
                 
                  foreach (var item in r){
                       RoleModel role= new RoleModel();
                       role.RoleName = item.ToString();
                       role.Username = userid;
                      rolelst.Add(role);
                       }
               
                  return Json(new { Result = "OK", Records = rolelst }, JsonRequestBehavior.AllowGet);
               
              }
              catch (Exception ex)
              {
                  return Json(new { Result = "ERROR", Message = ex.Message });
              }
          }
      
        
        //TODO : delete role
        //get the model and remove thr role for the user user 
        [HttpPost]
          public JsonResult DeleteRole(RoleModel roleModel)
        
         {

             if (!roleModel.RoleName.Equals(null))
             {
                 Thread.Sleep(50);
                 Roles.RemoveUserFromRole(roleModel.Username, roleModel.RoleName);
                 return Json(new { Result = "OK" });
             }
             else
                 return Json(new { Result = "OK" }, JsonRequestBehavior.AllowGet);
         }


        //TODO : Update role
        [HttpPost]
        public JsonResult AddUserRole(RoleModel roleModel)
        {

            if (!roleModel.RoleName.Equals(null))
            {
                Thread.Sleep(50);
                Roles.AddUserToRole(roleModel.Username, roleModel.RoleName);
                return Json(new { Result = "OK" });
            }
            else
                return Json(new { Result = "OK" }, JsonRequestBehavior.AllowGet);
        }
       
          #endregion

        #endregion







          [Authorize(Roles = "Admin")]
        //Listing Roles
        public ActionResult RoleIndex()
        {
            var roles = Roles.GetAllRoles();
            return View(roles);
        }


      [Authorize(Roles = "Admin")]
        public ActionResult RoleAddToUser()
        {
            SelectList list = new SelectList(Roles.GetAllRoles());
            ViewBag.Roles = list;

            return View();
        }

        /// <summary>
        /// Add role to the user
        /// </summary>
        /// <param name="RoleName"></param>
        /// <param name="UserName"></param>
        /// <returns></returns>
         [Authorize(Roles = "Admin")]
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult RoleAddToUser(string RoleName, string UserName)
        {

            if (Roles.IsUserInRole(UserName, RoleName))
            {
                ViewBag.ResultMessage = "This user already has the role specified !";
            }
            else
            {
                Roles.AddUserToRole(UserName, RoleName);
                ViewBag.ResultMessage = "Username added to the role succesfully !";
            }

            SelectList list = new SelectList(Roles.GetAllRoles());
            ViewBag.Roles = list;
            return View();
        }

         //<summary>
         //Get all the roles for a particular user
         //</summary>
         //<param name="UserName"></param>
         //<returns></returns>
        //[Authorize]
        //[HttpPost]
        //[ValidateAntiForgeryToken]
        //public ActionResult GetRoles(string UserName)
        //{
        //    if (!string.IsNullOrWhiteSpace(UserName))
        //    {
        //        ViewBag.RolesForThisUser = Roles.GetRolesForUser(UserName);
        //        SelectList list = new SelectList(Roles.GetAllRoles());
        //        ViewBag.Roles = list;
        //    }
        //    return View("RoleAddToUser");
        //}



          [Authorize(Roles = "Admin")]
        public JsonResult RoleDelete(string RoleName)
        {

            if (Roles.DeleteRole(RoleName))
            {
              //  ViewBag.ResultMessage = "Role deleted succesfully !";

                return Json(new { Status = RoleName +"لقد محوه" }, JsonRequestBehavior.AllowGet);
            }
            else
                return Json(new { Status = "Failure" }, JsonRequestBehavior.AllowGet);
        }


          [Authorize(Roles = "Admin")]
        public ActionResult ChangeLanguage(string lang)
        {
            new GUI.Ressources.SiteLanguages().SetLanguage(lang);
            return RedirectToAction("Register", "Account");
        }


          //create roles
        [Authorize (Roles="Admin")]
        public PartialViewResult RoleCreate()
        {
            return PartialView();
        }

         [Authorize(Roles = "Admin")]
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult RoleCreate(string RoleName)
        {

            Roles.CreateRole(Request.Form["RoleName"]);
            ViewBag.ResultMessage = "Role created successfully !";

            return PartialView();
            //return RedirectToAction("RoleIndex", "Account");
        }







        [HttpPost]
     
        [ValidateAntiForgeryToken]
        public ActionResult DeleteRoleForUser(string UserName, string RoleName)
        {

            if (Roles.IsUserInRole(UserName, RoleName))
            {
                Roles.RemoveUserFromRole(UserName, RoleName);
                ViewBag.ResultMessage = "Role removed from this user successfully !";
            }
            else
            {
                ViewBag.ResultMessage = "This user doesn't belong to selected role.";
            }
            ViewBag.RolesForThisUser = Roles.GetRolesForUser(UserName);
            SelectList list = new SelectList(Roles.GetAllRoles());
            ViewBag.Roles = list;


            return View("RoleAddToUser");
        }


       

        [HttpPost]
        public JsonResult DeleteProfile(int Id)
        {
            var p = db.UserProfiles.Find(Id);

            try
            {
              
                      db.UserProfiles.Remove(p);
          
                return Json(new { Result = "OK" });

            }

            catch (Exception ex)
            {
                return Json(new { Result = "ERROR", Message = ex.Message });
            }

        }




        //
        // GET: /Account/Login





        [AllowAnonymous]
        public ActionResult Login(string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;
            return View();
        }

        //
        // POST: /Account/Login

        [HttpPost]
        [AllowAnonymous]
      [ValidateAntiForgeryToken]
        public ActionResult Login(LoginModel model, string returnUrl)
        {

          

            if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))
            {
                return RedirectToLocal(returnUrl);
            }

            // If we got this far, something failed, redisplay form
            ModelState.AddModelError("", "The user name or password provided is incorrect.");
            return View(model);
        }

        //
        // POST: /Account/LogOff

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult LogOff()
        {
            Session["UserId"] = null;
            WebSecurity.Logout();
            


            return RedirectToAction("Index", "Home");
        }

        [HttpPost]
        public JsonResult LogOffAjax()
        {
            Session["UserId"] = null;
            WebSecurity.Logout();



            return Json(new { results = "done logged off" }, JsonRequestBehavior.AllowGet);
        }
        //
        // GET: /Account/Register

        [AllowAnonymous]
        public ActionResult Register()
        {
            return View();
        }

        //
        // POST: /Account/Register

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                try
                {
                    WebSecurity.CreateUserAndAccount(model.UserName, model.Password);
                    WebSecurity.Login(model.UserName, model.Password);
                    Session["UserId"] = WebSecurity.GetUserId(model.UserName);
                  
                    return RedirectToAction("Index", "Home");
                }
                catch (MembershipCreateUserException e)
                {
                    ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // POST: /Account/Disassociate

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Disassociate(string provider, string providerUserId)
        {
            string ownerAccount = OAuthWebSecurity.GetUserName(provider, providerUserId);
            ManageMessageId? message = null;

            // Only disassociate the account if the currently logged in user is the owner
            if (ownerAccount == User.Identity.Name)
            {
                // Use a transaction to prevent the user from deleting their last login credential
                using (var scope = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = System.Transactions.IsolationLevel.Serializable }))
                {
                    bool hasLocalAccount = OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
                    if (hasLocalAccount || OAuthWebSecurity.GetAccountsFromUserName(User.Identity.Name).Count > 1)
                    {
                        OAuthWebSecurity.DeleteAccount(provider, providerUserId);
                        scope.Complete();
                        message = ManageMessageId.RemoveLoginSuccess;
                    }
                }
            }

            return RedirectToAction("Manage", new { Message = message });
        }

        //
        // GET: /Account/Manage

        public ActionResult Manage(ManageMessageId? message)
        {
            ViewBag.StatusMessage =
                message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed."
                : message == ManageMessageId.SetPasswordSuccess ? "Your password has been set."
                : message == ManageMessageId.RemoveLoginSuccess ? "The external login was removed."
                : "";
            ViewBag.HasLocalPassword = OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
            ViewBag.ReturnUrl = Url.Action("Manage");
            return View();
        }

        //
        // POST: /Account/Manage

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Manage(LocalPasswordModel model)
        {
            bool hasLocalAccount = OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
            ViewBag.HasLocalPassword = hasLocalAccount;
            ViewBag.ReturnUrl = Url.Action("Manage");
            if (hasLocalAccount)
            {
                if (ModelState.IsValid)
                {
                    // ChangePassword will throw an exception rather than return false in certain failure scenarios.
                    bool changePasswordSucceeded;
                    try
                    {
                        changePasswordSucceeded = WebSecurity.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword);
                    }
                    catch (Exception)
                    {
                        changePasswordSucceeded = false;
                    }

                    if (changePasswordSucceeded)
                    {
                        return RedirectToAction("Manage", new { Message = ManageMessageId.ChangePasswordSuccess });
                    }
                    else
                    {
                        ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
                    }
                }
            }
            else
            {
                // User does not have a local password so remove any validation errors caused by a missing
                // OldPassword field
                ModelState state = ModelState["OldPassword"];
                if (state != null)
                {
                    state.Errors.Clear();
                }

                if (ModelState.IsValid)
                {
                    try
                    {
                        WebSecurity.CreateAccount(User.Identity.Name, model.NewPassword);
                        return RedirectToAction("Manage", new { Message = ManageMessageId.SetPasswordSuccess });
                    }
                    catch (Exception e)
                    {
                        ModelState.AddModelError("", e);
                    }
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // POST: /Account/ExternalLogin

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult ExternalLogin(string provider, string returnUrl)
        {
            return new ExternalLoginResult(provider, Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl }));
        }

        //
        // GET: /Account/ExternalLoginCallback

        [AllowAnonymous]
        public ActionResult ExternalLoginCallback(string returnUrl)
        {
            AuthenticationResult result = OAuthWebSecurity.VerifyAuthentication(Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl }));
            if (!result.IsSuccessful)
            {
                return RedirectToAction("ExternalLoginFailure");
            }

            if (OAuthWebSecurity.Login(result.Provider, result.ProviderUserId, createPersistentCookie: false))
            {
                return RedirectToLocal(returnUrl);
            }

            if (User.Identity.IsAuthenticated)
            {
                // If the current user is logged in add the new account
                OAuthWebSecurity.CreateOrUpdateAccount(result.Provider, result.ProviderUserId, User.Identity.Name);
                return RedirectToLocal(returnUrl);
            }
            else
            {
                // User is new, ask for their desired membership name
                string loginData = OAuthWebSecurity.SerializeProviderUserId(result.Provider, result.ProviderUserId);
                ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(result.Provider).DisplayName;
                ViewBag.ReturnUrl = returnUrl;
                return View("ExternalLoginConfirmation", new RegisterExternalLoginModel { UserName = result.UserName, ExternalLoginData = loginData });
            }
        }

        //
        // POST: /Account/ExternalLoginConfirmation

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult ExternalLoginConfirmation(RegisterExternalLoginModel model, string returnUrl)
        {
            string provider = null;
            string providerUserId = null;

            if (User.Identity.IsAuthenticated || !OAuthWebSecurity.TryDeserializeProviderUserId(model.ExternalLoginData, out provider, out providerUserId))
            {
                return RedirectToAction("Manage");
            }

            if (ModelState.IsValid)
            {
                // Insert a new user into the database
                using (var db = new AuteurContext())
                {
                    UserProfile user = db.UserProfiles.FirstOrDefault(u => u.UserName.ToLower() == model.UserName.ToLower());
                    // Check if user already exists
                    if (user == null)
                    {
                        // Insert name into the profile table
                        db.UserProfiles.Add(new UserProfile { UserName = model.UserName });
                        db.SaveChanges();

                        OAuthWebSecurity.CreateOrUpdateAccount(provider, providerUserId, model.UserName);
                        OAuthWebSecurity.Login(provider, providerUserId, createPersistentCookie: false);

                        return RedirectToLocal(returnUrl);
                    }
                    else
                    {
                        ModelState.AddModelError("UserName", "User name already exists. Please enter a different user name.");
                    }
                }
            }

            ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(provider).DisplayName;
            ViewBag.ReturnUrl = returnUrl;
            return View(model);
        }

        //
        // GET: /Account/ExternalLoginFailure

        [AllowAnonymous]
        public ActionResult ExternalLoginFailure()
        {
            return View();
        }

        [AllowAnonymous]
        [ChildActionOnly]
        public ActionResult ExternalLoginsList(string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;
            return PartialView("_ExternalLoginsListPartial", OAuthWebSecurity.RegisteredClientData);
        }

        [ChildActionOnly]
        public ActionResult RemoveExternalLogins()
        {
            ICollection<OAuthAccount> accounts = OAuthWebSecurity.GetAccountsFromUserName(User.Identity.Name);
            List<ExternalLogin> externalLogins = new List<ExternalLogin>();
            foreach (OAuthAccount account in accounts)
            {
                AuthenticationClientData clientData = OAuthWebSecurity.GetOAuthClientData(account.Provider);

                externalLogins.Add(new ExternalLogin
                {
                    Provider = account.Provider,
                    ProviderDisplayName = clientData.DisplayName,
                    ProviderUserId = account.ProviderUserId,
                });
            }

            ViewBag.ShowRemoveButton = externalLogins.Count > 1 || OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
            return PartialView("_RemoveExternalLoginsPartial", externalLogins);
        }

        #region Helpers
        private ActionResult RedirectToLocal(string returnUrl)
        {
            if (Url.IsLocalUrl(returnUrl))
            {
                return Redirect(returnUrl);
            }
            else
            {
                return RedirectToAction("Index", "Home");
            }
        }

        public enum ManageMessageId
        {
            ChangePasswordSuccess,
            SetPasswordSuccess,
            RemoveLoginSuccess,
        }

        internal class ExternalLoginResult : ActionResult
        {
            public ExternalLoginResult(string provider, string returnUrl)
            {
                Provider = provider;
                ReturnUrl = returnUrl;
            }

            public string Provider { get; private set; }
            public string ReturnUrl { get; private set; }

            public override void ExecuteResult(ControllerContext context)
            {
                OAuthWebSecurity.RequestAuthentication(Provider, ReturnUrl);
            }
        }

        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://go.microsoft.com/fwlink/?LinkID=177550 for
            // a full list of status codes.
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "User name already exists. Please enter a different user name.";

                case MembershipCreateStatus.DuplicateEmail:
                    return "A user name for that e-mail address already exists. Please enter a different e-mail address.";

                case MembershipCreateStatus.InvalidPassword:
                    return "The password provided is invalid. Please enter a valid password value.";

                case MembershipCreateStatus.InvalidEmail:
                    return "The e-mail address provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidAnswer:
                    return "The password retrieval answer provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "The password retrieval question provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidUserName:
                    return "The user name provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.ProviderError:
                    return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                case MembershipCreateStatus.UserRejected:
                    return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                default:
                    return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }
        }



        #endregion

        #region register author
        //Register Author//030215
        //bilel
        //TODO: add new account json
          [Authorize(Roles = "Admin")]
        [HttpPost]
        public JsonResult RegisterAuthor(RegisterModel model)
        {
            // Attempt to register the user

            var token = WebSecurity.CreateUserAndAccount(model.UserName, model.Password, new { Mail = model.Mail }, true);
          
            if (token != null)
            {
                Roles.AddUserToRole(model.UserName, model.Roles);
                var hosturl =
                    System.Web.HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) +
                    "/Account/ConfirmYourAccount?token=" + token;

                var confirmationLink = string.Format("<a href=\"{0}\">Clink to confirm your registration</a>", hosturl );
         //       TempData["message"] = string.Format(
         //"Thank you for registering. An email has been sent to {0}. " +
         //"Please check your email and use the enclosed link to finish registration.", model.UserName);
               //login
                WebSecurity.Login(model.UserName, model.Password);

                MailModel modelMail = new MailModel();
                modelMail.Body = confirmationLink;
                modelMail.To = model.Mail;
                modelMail.Subject = "";

                IUserMailer mailer = new UserMailer();
                mailer.SendLink(modelMail).Send();



                return Json(new { result = "ok" }, JsonRequestBehavior.AllowGet);
            }
            else
            {
                return Json(new { result = "ok" }, JsonRequestBehavior.AllowGet);
            }




        }
          [AllowAnonymous]
        public ActionResult ConfirmYourAccount(string ID)
        {
            var confirmationToken = Request["token"];
            if (!String.IsNullOrEmpty(confirmationToken))
            {
                
                    var user = WebSecurity.CurrentUserName;
               
                WebSecurity.ConfirmAccount(confirmationToken);

             
                TempResult temp = new TempResult();
                //proc stock
                //get userId by token
                var intu = db.Database.SqlQuery<TempResult>("GETUSERBYTOKEN @parma1", new SqlParameter("@parma1", confirmationToken)).ToList() ;
                 foreach (var item in intu)
                 {
                     temp.UserId = item.UserId;
                 }
                 string iduser = temp.UserId.ToString();
                 string Id = IntExtensions.Encode(iduser);
                 bool t = WebSecurity.ConfirmAccount(confirmationToken);
                 t = true;
                return RedirectToAction("Create", "Auteur", new { set5000544366auto = Id });     
             }


                TempData["message"] = string.Format(
                    "Your account was not confirmed, please try again or contact the website adminstrator.");
                return View("");     
             }


        [HttpGet]
          public JsonResult GetAuthorNames()
          {
              int IdAuthor = WebSecurity.CurrentUserId;
              var author = _auteurService.Find(IdAuthor);
              if (author != null)
              {
                  return Json(new { results = author },JsonRequestBehavior.AllowGet);
              }
              return Json(new { results = "Ko => Author Null" });
          }
      #endregion

        #region articles
    

        public ActionResult Articles()
        {
            return View();
        }
#endregion

    }
}

